package org.coody.framework.minicat.builder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.coody.framework.minicat.builder.iface.HttpBuilder;
import org.coody.framework.minicat.entity.HttpServletRequest;
import org.coody.framework.minicat.exception.NotConnectionException;
import org.coody.framework.minicat.util.StringUtil;

public class NioHttpBuilder extends HttpBuilder {

	private SocketChannel channel;

	public NioHttpBuilder(SocketChannel channel) {
		if(channel==null){
			throw new NotConnectionException("未实例化SocketChannel");
		}
		this.channel = channel;
	}

	@Override
	protected void buildRequest() throws Exception {
		this.request = new HttpServletRequest(getInputStream(channel));
	}

	private InputStream getInputStream(SocketChannel channel) throws IOException, InterruptedException {
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		try {
			while (channel.read(byteBuffer) > 0) {
				try {
					byteBuffer.flip();
					byte[] data = new byte[byteBuffer.remaining()];
					byteBuffer.get(data, 0, data.length);
					outStream.write(data);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					byteBuffer.flip();
					byteBuffer.clear();
				}
			}
			byte[] data = outStream.toByteArray();
			return new ByteArrayInputStream(data);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			outStream.close();
		}
	}

	@Override
	protected void flush() throws IOException {
		byte[] data = response.getOutputStream().toByteArray();
		if (StringUtil.isNullOrEmpty(data)) {
			return;
		}
		channel.write(ByteBuffer.wrap(data));
	}

}
